package com.xinxin.base.util.legacy;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * Copyright (C), 2018-2018
 * FileName:     HashtabUtil
 * Author:       未雨
 * E-mail:       lnb@love.com
 * Date:         2018-09-27 15:09
 * Description:  ${DESCRIPTION}
 * version:      0.1
 */
public class HashtabUtil {
    private HashtabUtil() {}

    /**
     * md5加密
     */
    public static String md5(String plainText) {
        // 返回字符串
        String md5Str = "";
        try {
            // 操作字符串
            StringBuffer buf = new StringBuffer();
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 添加要进行计算摘要的信息,使用 plainText 的 byte 数组更新摘要。
            md.update(plainText.getBytes());

            // 计算出摘要,完成哈希计算。
            byte b[] = md.digest();
            int i;

            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }

                if (i < 16) {
                    buf.append("0");
                }

                // 将整型 十进制 i 转换为16位，用十六进制参数表示的无符号整数值的字符串表示形式。
                buf.append(Integer.toHexString(i));

            }

            // 32位的加密
            md5Str = buf.toString();

            // 16位的加密
            // md5Str = buf.toString().md5Strstring(8,24);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5Str;
    }

    /**
     * 获得Hash码
     *
     * @param fileName
     * @param hashType
     * @return
     * @throws Exception
     */
    public static String getHash(String fileName, String hashType) throws Exception {
        InputStream fis;
        fis = new FileInputStream(fileName);
        byte[] buffer = new byte[1024];
        MessageDigest md5 = MessageDigest.getInstance(hashType);
        int numRead = 0;
        while ((numRead = fis.read(buffer)) > 0) {
            md5.update(buffer, 0, numRead);
        }
        fis.close();
        return toHexString(md5.digest());
    }

    private static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
            sb.append(hexChar[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    private static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
